<template>
  <el-dialog :title="id ? '编辑' : '添加'" :visible.sync="dialogVisible" :close-on-click-modal="false">
    <el-form ref="main-form" status-icon :model="mainQuery" :rules="rules" label-width="160px" label-position="left" :inline="false" size="mini" style="width: 400px">
      <!--        ID-->
      <el-form-item label="ID" size="mini" v-if="id != null">
        <el-input placeholder="" onfocus="this.select()" v-model="id" readonly></el-input>
      </el-form-item>

      <!--        分组-->
      <el-form-item label="分组" size="mini" prop="rateGroupId">
        <el-select v-model="mainQuery.rateGroupId" placeholder="未选择" clearable filterable>
          <el-option v-for="item in rateGroupOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <!--        原始币种-->
      <el-form-item label="原始币种" size="mini" prop="sourceCurrency">
        <el-select v-model="mainQuery.sourceCurrency" size="small" filterable clearable @change="fetchRate">
          <el-option :placeholder="placeholder || '未选择'" v-for="item in optionsList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <!--        目标币种-->
      <el-form-item label="目标币种" size="mini" prop="targetCurrency">
        <el-select v-model="mainQuery.targetCurrency" size="small" filterable clearable @change="fetchRate">
          <el-option :placeholder="placeholder || '未选择'" v-for="item in optionsList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <!--        汇率类型-->
      <el-form-item label="汇率类型" size="mini" prop="rateType">
        <el-select v-model="mainQuery.rateType" placeholder="未选择" clearable @change="fetchRate">
          <el-option v-for="item in myRateTypeOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="当前汇率" size="mini" prop="">
        <span>{{
          mainQuery.rate || (loadingRate ? "正在获取..." : "没有汇率信息")
        }}</span>
      </el-form-item>

      <el-form-item label="是否同步汇率" prop="">
        <el-radio-group v-model="mainQuery.syncType" @change="calcFinalRate">
          <el-radio v-for="item in syncTypeOptions" :label="item.value">{{
            item.label
          }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-if="mainQuery.syncType == 1">
        <el-form-item label="偏移类型" prop="">
          <el-radio-group v-model="mainQuery.offsetType" @change="calcFinalRate" :disabled="!mainQuery.rate">
            <el-radio v-for="item in offsetTypeOptions" :label="item.value">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="偏移量" size="mini" prop="offset">
          <el-input placeholder="" type="number" v-model.number="mainQuery.offset" @keyup.enter.native="submit" clearable @input="calcFinalRate" :disabled="!mainQuery.rate">
            <template slot="append" v-if="mainQuery.offsetType == 2">%</template>
          </el-input>
        </el-form-item>
      </template>

      <el-form-item label="平台汇率" size="mini" prop="finalRate">
        <el-input placeholder="" v-model="mainQuery.finalRate" @keyup.enter.native="submit" clearable @input="updateOffset"></el-input>
      </el-form-item>

      <el-form-item label="类型" prop="" v-if="id">
        <el-radio-group v-model="mainQuery.type">
          <el-radio v-for="item in typeOptions"  :disabled="!!id" :label="item.value">{{
            item.label
          }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="类型" prop="" v-else>
        <el-checkbox-group v-model="mainQuery.typeList">
          <el-checkbox v-for="(item,index) in typeOptions" :label="item.value" :key="index">{{
            item.label
            }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="状态" prop="">
        <el-radio-group v-model="mainQuery.status">
          <el-radio v-for="item in statusOptions" :label="item.value">{{
            item.label
          }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="修改时间" size="mini" v-if="data != null">
        {{ data.updateTime }}
      </el-form-item>

      <el-form-item label="创建时间" size="mini" v-if="data != null">
        {{ data.createTime }}
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <!-- <el-popover
          v-if="id != null"
          placement="top"
          width="160"
          v-model="popDeleteVisible">
          <p>确定删除吗？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="default" @click="popDeleteVisible = false">取消</el-button>
            <el-button type="danger" size="mini" @click="submitDel">确定</el-button>
          </div>
          <el-button type="danger" slot="reference"  size="small" style="float: left;" :loading="loading">删 除</el-button>
        </el-popover> -->

      <el-button @click="close" size="mini">取 消</el-button>
      <el-button @click="submit" size="mini" type="primary" :loading="loading">提 交</el-button>
    </div>
  </el-dialog>
</template>

<script>

import ApiMain from '@/api/exchangeRate.rateCustomized';
import ApiRate from '@/api/exchangeRate.rate';
import ApiRateBoc from '@/api/exchangeRate.rateBoc';
import CascaderCurrency from "@/views/exchangeRate/rateCustomized/components/cascader-currency";

export default {
  mixins: [
  ],
  props: [
    'rateGroupOptions',
    'currencyOptions',
    'rateTypeOptions',
    'syncTypeOptions',
    'offsetTypeOptions',
    'typeOptions',
    'statusOptions',
  ],
  components: {
    CascaderCurrency,
  },
  data() {
    return {
      placeholder: false,
      optionsList: [],
      dialogVisible: false,
      popDeleteVisible: false,
      loading: false,
      loadingRate: false,

      mainQueryRaw: null,
      mainQuery: {
        typeList: [],
        rateGroupId: '',
        sourceCurrency: '',
        targetCurrency: '',
        rateType: '',
        syncType: 0,
        rate: '',
        offset: 0,
        offsetType: 1,
        finalRate: '',
        type: 1,
        status: 1,
      },

      rules: {
        rateGroupId: [
          { required: true, message: '请选择分组', trigger: 'blur' },
        ],
        sourceCurrency: [
          { required: true, message: '请选择原始币种', trigger: 'blur' },
        ],
        targetCurrency: [
          { required: true, message: '请选择目标币种', trigger: 'blur' },
        ],
        rateType: [
          { required: true, message: '请选择中行汇率类型', trigger: 'blur' },
        ],
        offset: [
          { required: true, message: '请填写偏移量', trigger: 'blur' },
          { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: '最多两位小数', trigger: 'change' }
        ],
        finalRate: [
          { required: true, message: '请填写平台汇率', trigger: 'blur' },
        ],
      },

      id: null,
      data: null,
    }
  },
  computed: {
    myRateTypeOptions() {
      if (this.mainQuery.sourceCurrency[0] == "boc" && this.mainQuery.targetCurrency[0] == "boc") {
        return this.rateTypeOptions;
      }
      else {
        return this.rateTypeOptions.slice(0, 4);
      }
    },

  },
  mounted() {
    this.mainQueryRaw = Object.copy(this.mainQuery);
  },

  methods: {

    show(id = null) {

      this.reset();


      if (id) {
        this.id = id;
        this.fetchData();
      }

      this.dialogVisible = true;
    },

    close() {
      this.dialogVisible = false;
      this.reset()
      this.$emit('dialog-close');
    },

    async reset() {
       this.id = null;
      this.data = null;
      // this.mainQuery = Object.copy(this.mainQueryRaw);
      this.$refs['main-form'] && this.$refs['main-form'].resetFields();
      this.optionsList = await ApiRateBoc.getrateBocOptions()
     
    },

    async fetchData() {

      this.loading = true;

      try {
        var re = await ApiMain.info({ id: this.id })
        this.data = re;
      } catch (err) {
        this.data = null;
      }

      this.renderData();

      this.loading = false;

    },

    renderData() {

      this.mainQuery.rateGroupId = this.data.rateGroupId;
      this.mainQuery.rateType = this.data.rateType;
      this.mainQuery.syncType = this.data.syncType;
      this.mainQuery.rate = this.data.rate / 1e4;
      this.mainQuery.offsetType = this.data.offsetType;
      this.mainQuery.type = this.data.type;
      this.mainQuery.status = this.data.status;
      this.mainQuery.sourceCurrency = this.data.sourceCurrency;
      this.mainQuery.targetCurrency = this.data.targetCurrency;

      if (this.data.offsetType == 1) {
        this.mainQuery.offset = this.data.offsetValue / 1e4;
      }
      else if (this.data.offsetType == 2) {
        this.mainQuery.offset = this.data.offsetPercentage / 100;
      }

      this.mainQuery.finalRate = this.data.finalRate / 1e4;

      if (this.syncType == 1) {
        this.fetchRate();
      }
      else {
        this.calcFinalRate();
      }
    },

    verifyForm() {
      var bool = true;
      this.$refs['main-form'].validate((valid) => bool = valid);
      return bool;
    },

    async fetchRate() {

      // {"type":1,"srcCurrency":"HKD","destCurrency":"CNY"}

      // 参数不齐全
      if (!this.mainQuery.rateType || !this.mainQuery.sourceCurrency || !this.mainQuery.targetCurrency) {
        this.mainQuery.rate = null;
        return false;
      }

      var req = {
        type: this.mainQuery.rateType,
        srcCurrency: this.mainQuery.sourceCurrency,
        destCurrency: this.mainQuery.targetCurrency,
      };

      if (Array.isArray(req.srcCurrency)) {
        req.srcCurrency = req.srcCurrency[1];
      }

      if (Array.isArray(req.destCurrency)) {
        req.destCurrency = req.destCurrency[1];
      }

      // 原始币种和目标币种相同
      // if (req.srcCurrency == req.destCurrency) {
      //   this.mainQuery.rate = null;
      //   return false;
      // }

      this.mainQuery.rate = null;
      this.loadingRate = true;

      try {
        var re = await ApiRate.getRate(req);
        if (re.rate <= 0) {
          this.mainQuery.rate = null;
        }
        else {
          this.mainQuery.rate = re.rate / 1e4;
        }
      } catch (err) {
        this.mainQuery.rate = null;
      }

      this.loadingRate = false;

      this.calcFinalRate();
    },

    // 根据偏移量计算平台汇率
    calcFinalRate() {

      if (this.mainQuery.syncType != 1) return false;
      if (this.mainQuery.rate === null) return false;
      if (this.mainQuery.rate == '') return false;

      var finalRate = 0;
      var rate = this.mainQuery.rate;

      if (this.mainQuery.offsetType == 1) {
        // 数值
        finalRate = rate * 1e4 + this.mainQuery.offset * 1e4;
      }
      else {
        // 百分比
        finalRate = rate * 1e4 * (1 + (this.mainQuery.offset / 100));
      }

      this.mainQuery.finalRate = Math.round(finalRate) / 1e4;
    },

    // 根据平台汇率反算偏移量
    updateOffset() {

      if (this.mainQuery.syncType != 1) return false;
      if (this.mainQuery.rate === null) return false;
      if (this.mainQuery.rate == '') return false;

      var finalRate = Math.round(this.mainQuery.finalRate * 1e4);
      var rate = Math.round(this.mainQuery.rate * 1e4);
      var offset = this.calcOffset(rate, finalRate, this.mainQuery.offsetType);

      this.mainQuery.offset = offset;
    },

    // 根据中行汇率,目标汇率,偏移类型反算偏移量
    calcOffset(rate, finalRate, offsetType) {

      var offset = 0;

      if (offsetType == 1) {
        // 数值
        offset = (finalRate - rate) / 1e4;
      }
      else {
        // 百分比
        offset = Math.round((finalRate - rate) / rate * 10000) / 100;
      }

      return offset;
    },

    buildQuery() {
        delete this.mainQuery[""]
      var req = Object.copy(this.mainQuery);

      req.offsetValue = 0;
      req.offsetPercentage = 0;

      req.rate = req.rate * 1e4;
      req.finalRate = req.finalRate * 1e4;

      // 不同步的情况
      if (req.syncType == 0) {

        // 根据中行汇率和目标汇率反算偏移量
        req.offsetType = 1;
        req.offset = this.calcOffset(req.rate, req.finalRate, req.offsetType);
      }

      if (req.offsetType == 1) {
        req.offsetValue = Math.round(req.offset * 1e4);
      }
      else {
        req.offsetPercentage = Math.round(req.offset * 100);
      }

      if (Array.isArray(req.sourceCurrency)) {
        req.sourceCurrency = req.sourceCurrency[1];
      }

      if (Array.isArray(req.targetCurrency)) {
        req.targetCurrency = req.targetCurrency[1];
      }

      // var t = {
      //   '中行汇率': req.rate / 1e4,
      //   '平台汇率': req.finalRate / 1e4,
      //   '是否同步': req.syncType == 1 ? '是' : '否',
      //   '偏移类型': req.offsetType == 1 ? '数值' : '百分比',
      //   '偏移量' : req.offsetType == 1 ? req.offsetValue / 1e4 : req.offsetPercentage / 100 + '%',
      // };

      // console.log(t);

      return req;
    },

    async submit() {

      if (!this.verifyForm()) return false;

      this.loading = true;

      try {
        this.id ? await this.submitSet() : await this.submitAdd();
      } catch (err) {
        console.error(err)
      }

      this.loading = false;
    },


    async submitAdd() {

      var req = this.buildQuery();

       delete req.type

       
      await ApiMain.add(req);
      this.$message({ message: '添加成功', type: 'success' });
      this.close();
    },

    async submitSet() {

      var req = this.buildQuery();


      req.id = this.id;
      
      delete req.typeList

      await ApiMain.set(req);
      this.$message({ message: '修改成功', type: 'success' });
      this.close();

    },

    async submitDel() {

    },
  }
}
</script>

<style>
</style>
